﻿<%@ Page Language="C#" %>
<%@ Register TagPrefix="IRL" TagName="DatePicker" Src="DatePicker.ascx" %>

<%@ Import Namespace="IRL.Utilities" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">    
    public const int CURRENT_MODULE = 54;
    
    int proposalID = 0, milestoneID = 0;
    bool HasWriteAccess = false;
    float Amount = 0;
    
    protected void Page_Load(object src, EventArgs e)
    {
        Security SysAcc = new Security(CURRENT_MODULE);
        // check is authenticate
        SysAcc.Authenticate();
        HasWriteAccess = SysAcc.IsAuthorized(2);
        
        // load reminder count        
        //Mics.loadReminderCount(lblReminderCount);
        
        if (Request.QueryString["pid"] == null)
        {
            // There is no pid QueryString                
        }
        else
        {                        
            proposalID = int.Parse(Request.QueryString["pid"]);
            
            if (Request.QueryString["mid"] != null)
                milestoneID = int.Parse(Request.QueryString["mid"]);

            if (Page.IsPostBack)
            {
                if (HasWriteAccess)
                {
                    saveData();
                }
            }
            else
            {
                loadData();
            }
        }
    }

    void saveData()
    {
        // Save to database
        milestoneID = int.Parse(txtMilestoneID.Text);
        proposalID = int.Parse(txtProposalID.Text);
        string billingType = cboMilestoneType.SelectedValue;
        string note = txtNote.Text;
        string[] billingDate = txtBillingDate.CalendarDate.Split('-');
        Array.Reverse(billingDate);
        float amount = float.Parse(txtAmount.Text);
        //float.TryParse(txtAmount.Text, out amount);
        string[] paymentDate = txtPaymentDate.CalendarDate.Split('-');
        Array.Reverse(paymentDate);
        int status = int.Parse(cboStatus.SelectedValue);
        bool preBillingReminder = chkPreBilling.Checked;
        object preBillingReminderDate = txtPreBillingAlert.CalendarDate;
        bool postBillingReminder = chkPostBilling.Checked;
        object postBillingReminderDate = txtPostBillingAlert.CalendarDate;
        if (preBillingReminderDate.ToString() == "")
        {
            preBillingReminderDate = DBNull.Value;
        }
        else
        {
            string[] dateElem = preBillingReminderDate.ToString().Split('-');
            Array.Reverse(dateElem);
            preBillingReminderDate = DateTime.Parse(String.Join("/", dateElem));
        }
        if (postBillingReminderDate.ToString() == "")
        {
            postBillingReminderDate = DBNull.Value;
        }
        else
        {
            string[] dateElem = postBillingReminderDate.ToString().Split('-');
            Array.Reverse(dateElem);
            postBillingReminderDate = DateTime.Parse(String.Join("/", dateElem));
        }
        
        // run store procedure
        object connStr = ConfigurationSettings.AppSettings["sqlConn"];
        using (SqlConnection conn = new SqlConnection(connStr.ToString()))
        {
            SqlCommand cmd = new SqlCommand("sp_SaveMilestone", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@milestoneid", SqlDbType.Int).Value = milestoneID;
            cmd.Parameters.Add("@proposalid", SqlDbType.Int).Value = proposalID;
            cmd.Parameters.Add("@milestonetype", SqlDbType.NVarChar, 30).Value = billingType;
            cmd.Parameters.Add("@note", SqlDbType.NVarChar, 30).Value = note;
            cmd.Parameters.Add("@billingdate", SqlDbType.DateTime).Value = String.Join("/", billingDate);
            cmd.Parameters.Add("@amount", SqlDbType.Money).Value = amount;
            cmd.Parameters.Add("@paymentdate", SqlDbType.DateTime).Value = String.Join("/", paymentDate);
            cmd.Parameters.Add("@status", SqlDbType.Int).Value = status;
            cmd.Parameters.Add("@prebillingreminder", SqlDbType.Bit).Value = preBillingReminder;
            cmd.Parameters.Add("@prebillingreminderdate", SqlDbType.DateTime).Value = preBillingReminderDate;
            cmd.Parameters.Add("@postbillingreminder", SqlDbType.Bit).Value = postBillingReminder;
            cmd.Parameters.Add("@postbillingreminderdate", SqlDbType.DateTime).Value = postBillingReminderDate;

            conn.Open();
            milestoneID = (int)cmd.ExecuteScalar();
        }

        lblSaveStatus.Text = "Data is already saved to the database.<br //><br //>";
        txtMilestoneID.Text = milestoneID.ToString();
        txtProposalID.Text = proposalID.ToString();
        // Redirect
        Response.Redirect("listMilestones.aspx?pid=" + proposalID);
    }

    void loadData()
    {
        // Control Data-Binding
        List.fillList(cboMilestoneType, "sp_Select_cms_Lookup 'billing_type', 0, 1");
        List.fillList(cboStatus, "sp_Select_cms_Lookup 'milestone_status'");
        txtPreBillingAlert.Enabled = false;
        txtPostBillingAlert.Enabled = false;
        if (!HasWriteAccess)
        {
            SaveButton.Visible = false;
        }
        
        // Load Data
        object connStr = ConfigurationSettings.AppSettings["sqlConn"];
        using (SqlConnection conn = new SqlConnection(connStr.ToString()))
        {
            SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [cms_Projects] WHERE [ProposalID]=" + proposalID, conn);
            conn.Open();
            int projectExist = (int)cmd.ExecuteScalar();
            if (projectExist == 1)
            {                
                txtProposalID.Text = proposalID.ToString();
                cmd.CommandText = "SELECT * FROM [cms_Milestones] WHERE [MilestoneID]=" + milestoneID + " AND [ProposalID]=" + proposalID;
                SqlDataReader dr = cmd.ExecuteReader();
                bool loadMilestoneSuccess = false;
                if (dr.Read())
                {
                    txtMilestoneID.Text = milestoneID.ToString();
                    cboMilestoneType.SelectedValue = dr["MilestoneType"].ToString();
                    txtNote.Text = dr["Note"].ToString();
                    txtBillingDate.CalendarDate = ((DateTime)dr["BillingDate"]).ToString("dd-MM-yyyy");
                    txtAmount.Text = String.Format("{0:#0.00}", dr["Amount"]);
                    txtFigure.Value = txtAmount.Text;
                    txtPaymentDate.CalendarDate = ((DateTime)dr["PaymentDate"]).ToString("dd-MM-yyyy");
                    cboStatus.SelectedValue = dr["Status"].ToString();
                    loadMilestoneSuccess = true;
                    Amount = Convert.ToSingle(dr["Amount"]);
                }
                dr.Close();
                if (loadMilestoneSuccess)
                {
                    cmd.CommandText = "SELECT * FROM [cms_Reminders] WHERE [MilestoneID]=" + milestoneID;
                    dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        switch (dr.GetInt32(1))
                        {
                            case 1:
                                chkPreBilling.Checked = dr.GetBoolean(3);
                                txtPreBillingAlert.Enabled = dr.GetBoolean(3);
                                if(dr.GetValue(2)!= DBNull.Value)
                                    txtPreBillingAlert.CalendarDate = dr.GetDateTime(2).ToString("dd-MM-yyyy");
                                break;
                            case 2:
                                chkPostBilling.Checked = dr.GetBoolean(3);
                                txtPostBillingAlert.Enabled = dr.GetBoolean(3);
                                if (dr.GetValue(2) != DBNull.Value)
                                    txtPostBillingAlert.CalendarDate = dr.GetDateTime(2).ToString("dd-MM-yyyy");
                                break;
                        }
                    }
                    dr.Close();
                }
                // get project info
                projectInfo();
            }
            else
            {
                // invalid pid Query string
                Response.Redirect("default2.aspx");
                //txtProposalID.Text = "0";                
            }
        }
    }

    void projectInfo()
    {
        object connStr = ConfigurationSettings.AppSettings["sqlConn"];
        using (SqlConnection conn = new SqlConnection(connStr.ToString()))
        {
            SqlCommand cmd = new SqlCommand("sp_Billing_Total", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@proposalid", SqlDbType.Int).Value = proposalID;
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    ViewState.Add(dr.GetName(i), dr[i]);
                }
                string StrScript = "<script language=\"javascript\">\n" +
                                    "var project_cost=" + dr["Costs"].ToString() + ";\n" +
                                    "var total_payment=" + dr["Total"].ToString() + ";\n" +
                                    "var current_value=" + Amount + ";\n" +
                                    "<" + "/" + "script>";
                this.RegisterClientScriptBlock("Init", StrScript);
            }
        }
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <title>Indochina Research</title>
    
    <link href="../css/global.css" rel="stylesheet" type="text/css" />
    <link href="css/cms.css" rel="stylesheet" type="text/css" />
    
    
    <link href="cal/popcalendar.css" type="text/css" rel="stylesheet" />
    <script language="javascript" src="cal/popcalendar.js"></script>
    <script language="javascript" src="cal/holidays.js"></script>
    <script language="javascript" src="includes/checkDate.js"></script>
    
    <script type="text/javascript" language="javascript">
        
        function validateInfo(){
            var f = document.frmMilestone;                                  
            
            //Initialise variables
	        var errorMsg = "";
	        var errorMsgLong = "";
            
            //check Type
            //if(f.txtNote.value.length==0){
            //    errorMsg += "\n\tType \t\t- You must enter Type";
            //}
            
            //check Billing date
            if(f.txtBillingDate_txt_Date.value.length==0){
                errorMsg += "\n\tBillingDate \t- You must select Billing Date";
            }else if(!isDate(f.txtBillingDate_txt_Date.value)){
                errorMsg += "\n\tBillingDate \t- Please enter valid Billing Date";
            }
            
            //check Amount
            if(isNaN(f.txtAmount.value) || f.txtAmount.value.length==0){
                errorMsg += "\n\tAmount \t\t- You must enter valid Amount"
            }
            
            //check Payment date
            if(f.txtPaymentDate_txt_Date.value.length==0){
                errorMsg += "\n\tPaymentDate \t- You must select Payment Date";
            }else if(!isDate(f.txtPaymentDate_txt_Date.value)){
                errorMsg += "\n\tPaymentDate \t- Please enter valid Payment Date";
            }
            
            //check pre-billing reminder
            if(f.chkPreBilling.checked){
                if(f.txtPreBillingAlert_txt_Date.value.length==0){
                    errorMsg += "\n\tPreBillingAlert \t- You must select Pre-Billing Alert Date";
                }else if(!isDate(f.txtPreBillingAlert_txt_Date.value)){
                    errorMsg += "\n\tPreBillingAlert \t- Please enter valid Pre-Billing Alert Date";
                }
            }
            
            //check post-billing reminder
            if(f.chkPostBilling.checked){
                if(f.txtPostBillingAlert_txt_Date.value.length==0){
                    errorMsg += "\n\tPostBillingAlert \t- You must select Post-Billing Alert Date";
                }else if(!isDate(f.txtPostBillingAlert_txt_Date.value)){
                    errorMsg += "\n\tPostBillingAlert \t- Please enter valid Post-Billing Alert Date";
                }
            }
                       
            //If there is aproblem with the form then display an error
	        if ((errorMsg != "") || (errorMsgLong != "")){
			        msg = "_______________________________________________________________\n\n";
			        msg += "The form has not been submitted because there are problem(s) with the form.\n";
			        msg += "Please correct the problem(s) and re-submit the form.\n";
			        msg += "_______________________________________________________________\n\n";
			        msg += "The following field(s) need to be corrected: -\n";

			        errorMsg += alert(msg + errorMsg + "\n" + errorMsgLong);
			        return;
	        } 
            
            f.submit();
        }
        
        function validateAmount(){
            var f = document.frmMilestone;
            var available_value = project_cost - total_payment + current_value;
            var errMsg = "";
            
            if(f.optAmount[0].checked){
                if(f.txtFigure.value>available_value){
                    errMsg += "The amount does not balanced.\n\n" + 
                                "Please revised the figure.";                    
                }else{
                    f.txtAmount.value = f.txtFigure.value;
                }
            }else if(f.optAmount[1].checked){
                var value = Math.round(f.txtFigure.value*project_cost/100*100)/100;
                if(value>available_value){
                    errMsg += "The amount does not balanced.\n\n" + 
                                "Please revised the figure.";
                }else{
                    f.txtAmount.value = value;
                }
            }else{
                
            }
            // show Message
            if(errMsg != ""){
                alert(errMsg);
                // use information DIV
                f.txtFigure.focus();
                f.txtFigure.select();
            }
        }
        
        // select amount option
        function optAmount_Change(){
            var f = document.frmMilestone;
            var available_value = project_cost - total_payment + current_value;
            var value = f.txtAmount.value;
            
            f.txtFigure.readOnly = false;
            if(f.optAmount[0].checked){
                f.txtFigure.value = value;
            }else if(f.optAmount[1].checked){
                f.txtFigure.value = Math.round(value/project_cost*100*100)/100;
            }else{
                f.txtFigure.readOnly = true;
                f.txtFigure.value = available_value;
                f.txtAmount.value = available_value;                
            }
        }
    </script>    
</head>
<body>
<table width="773" border="0" cellspacing="0" cellpadding="0" align="center">
	<tr>
		<td width="765" height="540" align="center" valign="top" style="border:solid 1px #10147e;" >
			<!-- header -->
			<table border="0" cellpadding="0" cellspacing="0" width="100%">
				<tr bgcolor="#F4F4F9">
					<td colspan="3" align="right" style="padding:10px;">
						<b class="blueL">Client Management System</b>
					</td>
				</tr>
				<tr>
					<td class="wave_l">&nbsp;</td>
					<td><img src="../images/wave_logo.jpg" width="107" height="83"></td>
					<td class="wave_r">&nbsp;</td>
				</tr>
				<tr>
					<td colspan="3" style="padding:0 20px;">
						<div style="background-color:#bcb3d5; padding:5px 10px;">
							<span style="float:right">
							    <a class="blue" href="javascript:history.go(-1);">&laquo; Back</a>
							</span>
							<span class="pathmap">
								<a href="default.aspx" >CPanel</a> :: 
								<a href="default2.aspx">Ops Files</a> :: 
								<a href="listMilestones.aspx?pid=<%=proposalID %>">Billing notes</a> ::
								Add/Update note
						  </span>
						</div>
						<br />
						
						
					</td>
				</tr>
				
			</table>
			
			<!-- body -->
			<form id="frmMilestone" method="post" runat="server">
			<table border="0" width="100%" cellspacing="0" cellpadding="0">
				<tr>
					<td valign="top" style="padding-left:20px;">
						<div id="sidebar" class="sidebar">                            
	                        <h3>Project Info:</h3>
	                        <div class="block">
		                        <div><h5><%=ViewState["ProjectName"].ToString() %> (<%=ViewState["ProjectCode"].ToString().TrimEnd() %>)</h5></div>
	                        </div>
	                        <div class="block">
		                        <div><h5>Duration</h5></div>
		                        <table border="0" cellpadding="2" style="padding-left:10px;">
		                            <tr>
		                                <td>From</td>
		                                <td>:</td>
		                                <td><%=((DateTime)ViewState["StartDate"]).ToString("dd-MM-yyyy") %></td>
		                            </tr>
		                            <tr>
		                                <td>To</td>
		                                <td>:</td>
		                                <td><%=((DateTime)ViewState["EndDate"]).ToString("dd-MM-yyyy") %></td>
		                            </tr>
		                        </table>
	                        </div>
	                        <div class="block">
		                        <div><h5>Value</h5></div>
		                        <table border="0" cellpadding="2" style="padding-left:10px;">
		                            <tr>
		                                <td>Project cost</td>
		                                <td>:</td>
		                                <td><%=String.Format("{0:#,#0}", ViewState["Costs"]) %></td>
		                            </tr>
		                            <tr>
		                                <td>Total payment</td>
		                                <td>:</td>
		                                <td><%=String.Format("{0:#,#0}", ViewState["Total"]) %></td>
		                            </tr>
		                        </table>
	                        </div><br />
                        </div>
					</td>
					<td width="10"><img src="../images/spacer.gif" width="10" height="1" /></td>
					<td valign="top">
						<!-- data row -->
                        <div style="width:480px; overflow:auto; overflow-y:visible">
                            <asp:TextBox ID="txtMilestoneID" Text="0" Visible="false" runat="server" />
                            <asp:TextBox ID="txtProposalID" Visible="false" runat="server" />
                            <asp:Label CssClass="orange" ID="lblSaveStatus" runat="server" />
                            <table border="0" cellspacing="0" cellpadding="3">
                                <tr>
                                    <td width="125" height="25" align="right">
                                        Type :</td>
                                    <td>
                                        <asp:DropDownList ID="cboMilestoneType" runat="server" /> 
                                        <asp:TextBox ID="txtNote" Columns="8" runat="server" /></td>
                                </tr>
                                <tr>
                                    <td height="25" align="right">
                                        Billing Date :</td>
                                    <td>
                                        <IRL:DatePicker ID="txtBillingDate" runat="server" /></td>
                                </tr>
                                <tr>
                                    <td height="25" align="right">
                                        Amount :</td>
                                    <td class="normalsize">                                        
                                            <input id="optAmount1" type="radio" name="optAmount" value="1" checked="checked" onClick="optAmount_Change()" /><label for="optAmount1">&nbsp;USD</label>
                                            <input id="optAmount2" type="radio" name="optAmount" value="2" onClick="optAmount_Change()" /><label for="optAmount2">&nbsp;Percent</label>  
                                            <input id="optAmount3" type="radio" name="optAmount" value="3" onClick="optAmount_Change()" /><label for="optAmount3">&nbsp;Remaining (<script type="text/javascript">document.write(project_cost - total_payment + current_value);</script>)</label>
                                        </td>
                                </tr>
                                <tr>
                                    <td>&nbsp;</td>
                                    <td class="normalsize">
                                        <div><input id="txtFigure" name="txtFigure" size="10" onBlur="validateAmount();" runat="server" />
                                        =<asp:TextBox CssClass="num" Columns="10" ID="txtAmount" runat="server"
                                            style="border-style:none;border-width:0;" />&nbsp;<span
                                            class="fldNote">$USD</span></div></td>
                                </tr>
                                <tr>
                                    <td height="25" align="right">
                                        Payment Date :</td>
                                    <td>
                                        <IRL:DatePicker ID="txtPaymentDate" runat="server" /></td>
                                </tr>
                                <tr>
                                    <td height="25" align="right">
                                        Status :</td>
                                    <td>
                                        <asp:DropDownList ID="cboStatus" runat="server" /></td>
                                </tr>
                                <tr>
                                    <td align="right">&nbsp;</td>
                                    <td>&nbsp;</td>
                                </tr>
                                <tr>
                                    <td>
                                        <h5 class="blueL">
                                            Reminders</h5></td>
                                    <td>&nbsp;</td>
                                </tr>
                                <tr>
                                    <td colspan="2">
                                        <img src="images/line.gif" /></td>
                                </tr>
                                <tr>
                                    <td align="right">&nbsp;</td>
                                    <td>&nbsp;</td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:CheckBox ID="chkPreBilling" Text="Pre-Billing" onclick="enabledCalendar('txtPreBillingAlert', this.checked, txtBillingDate_txt_Date.value, -7)"
                                            runat="server" /></td>
                                    <td>
                                        <IRL:DatePicker ID="txtPreBillingAlert" runat="server" /></td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:CheckBox ID="chkPostBilling" Text="Post-Billing" onclick="enabledCalendar('txtPostBillingAlert', this.checked, txtPaymentDate_txt_Date.value, -7)"
                                            runat="server" /></td>
                                    <td>
                                        <IRL:DatePicker ID="txtPostBillingAlert" runat="server" /></td>
                                </tr>
                                <tr>
                                    <td align="right">&nbsp;</td>
                                    <td>&nbsp;</td>
                                </tr>
                                <tr>
                                    <td align="right">&nbsp;</td>
                                    <td>
                                        <table id="SaveButton" border="0" cellpadding="2" cellspacing="0" runat="server">
                                            <tr>
                                                <td width="70">
                                                    <a class="cmd" href="javascript:validateInfo();">Save</a></td>
                                                <td width="5">&nbsp;</td>
                                                    
                                                
                                                <td width="80">
                                                    <a class="cmd" href="javascript:history.go(-1);">Cancel</a></td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </td>
                </tr>
			</table>
			</form>
			
		</td>
		
		<td width="6" class="rightShadow" valign="top">
			<img src="../images/white.gif" width="6" height="6" /></td>
	</tr>
	
	<!-- bottom shadow -->
	<tr>
		<td height="6" class="bottomShadow">
			<img src="../images/white.gif" width="6" height="6" /></td>
		
		<td width="6" height="6">
			<img src="../images/shadow_corner.gif" width="6" height="6" /></td>
	</tr>
</table>


</body>
</html>
